# -*- coding: UTF-8 -*-
# @ Author : 游于艺
# @ QQ : 58012007
# @ File: zy_day17_游于艺.py
# @ Time: 2018/3/9 12:30

# """
# 1.计算range(1,99999)的总和,采取三种方式,第一:重复10次计算总时间;
#  第二:开启十个子线程去计算;第三:开启十个进程去计算,然后对比耗时
# """
# def mk_sum():
#     return sum(range(1,99999))
# import time
# # 第一：重复10次计算总时间
# def count10():
#     time1 = time.time()
#     for i in range(10):
#         mk_sum()
#     time2 = time.time()
#     print("重复10次计算总时间为：{}".format(time2-time1))
#
# # 第二：开启十个子线程去计算;
# from threading import Thread,current_thread
# def thr10():
#     time1 = time.time()
#     thread_list = [Thread(target=mk_sum,args=()) for num in range(10)]
#     for thr in thread_list:
#         thr.start()
#         thr.join()
#     time2 = time.time()
#     print("开启十个子线程计算总时间为：{}".format(time2 - time1))
#
# # 第三:开启十个进程去计算
# from multiprocessing import Process,Pool
# def pro10():
#     time1 = time.time()
#     pro = Process(target=mk_sum, args=())
#     pro.start()
#     pro.join()
#     time2 = time.time()
#     print("开启十个进程计算总时间为：{}".format(time2 - time1))
#
# # 开启进程池
# def pro_pool(cpunum):
#     time1 = time.time()
#     pool = Pool(cpunum) #最大进程数目
#     for num in range(cpunum):
#         pool.apply_async(mk_sum,args=())
#     pool.close()
#     pool.join()
#     time2 = time.time()
#     print("进程池计算总时间为：{}".format(time2 - time1))
# if __name__ == '__main__':
#     count10() #重复10次
#     thr10() #十个线程跑
#     pro10() #十个进程跑
# #     进程池
#     pro_pool(4)
#
#
#
# # 耗时结论：十个进程跑 > 十个线程跑 > 重复10次 > 进程池
# """
# 2.将第一题计算十次改为使用线程池去计算,线程池线程个数由你自己电脑cpu逻辑核数决定
#
# 【见上面是进程池】
# """






# 作业修改

from multiprocessing import Pool,cpu_count
from multiprocessing.dummy import Pool as ThreadPool       #线程池的pool会和上面进程池pool重复
import time

def c_time(func):
    def inner(num):
        time1 = time.time()
        func(num)
        time2 = time.time()
        print("计算花费的时间为%s" % str(time2-time1))
    return inner

# 第一：重复10次计算总时间
@c_time
def c_10time(num):
    for i in range(10):
        sum(range(num))

def p_10time(num):
    for i in range(10):
        sum(range(num))

# 第二：开启十个子进程去计算;
@c_time
def process_10time(num):
    print("cpu核数：",cpu_count())
    pools = Pool(cpu_count())    #创建进程池对象
    for i in range(10):
        pools.apply_async(p_10time,(num,))
    pools.close()
    pools.join()


# 第三:开启十个线程去计算
@c_time
def thread_10time(num):
    pools = ThreadPool(cpu_count())  # 创建进程池对象
    for i in range(10):
        pools.apply_async(p_10time, (num,))
    pools.close()
    pools.join()

# 开启进程池


if __name__ == '__main__':
    # c_10time(999999)
    process_10time(999999)
    # thread_10time(999999)

# python在win平台下使用多进程一定要放在if __name__ == '__main__':主入口下
# 多进程--->import当前脚本文件---->构建多进程（递归）---->解释器会奔溃